package com.betterjr.modules.risk.loan.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.betterjr.common.config.SpringPropertyResourceReader;
import com.betterjr.common.utils.BTAssert;
import com.betterjr.common.utils.Collections3;
import com.betterjr.common.utils.JedisUtils;

public class BetterAuthorizerToken {

    private static final String BETTER_REDIS_TOKEN = "betterAuthronizedTimeToken";

    private static final String BETTER_AUTHRONIZED_API_URL = "/oauth/token";

    private static String clientId = SpringPropertyResourceReader.getProperty("web.better.authorizer.client_id",
            "client_1");
    private static String clientSecret = SpringPropertyResourceReader.getProperty("web.better.authorizer.client_secret",
            "123456");
    private static String prifixUrl = SpringPropertyResourceReader.getProperty("web.prefix.fund.system.url", "");

    private static Map<String, String> paramMap = new HashMap<>();

    static {

        paramMap.put("grant_type", "client_credentials");
        paramMap.put("client_id", clientId);
        paramMap.put("client_secret", clientSecret);
        paramMap.put("scope", "all");

    }

    public static void addHeadParam(String headKey, String headValue) {

        if (!Collections3.isEmpty(paramMap)) {
            if (StringUtils.isNoneBlank(headKey) && StringUtils.isNoneBlank(headValue)) {
                paramMap.put(headKey, headValue);
            }
        }

    }

    public static void removeHeadParam(String headKey) {
        if (!Collections3.isEmpty(paramMap)) {
            if (StringUtils.isNoneBlank(headKey) && paramMap.containsKey(headKey)) {
                paramMap.remove(headKey);
            }
        }
    }

    public static String getHttpUri() {

        StringBuilder sb = new StringBuilder();

        sb.append(prifixUrl).append(BETTER_AUTHRONIZED_API_URL).append("?");
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {

            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");

        }

        return sb.substring(0, sb.length() - 1).toString().replaceAll("\"", "");

    }

    public synchronized static String getToken() {

        String token = JedisUtils.get(BETTER_REDIS_TOKEN);
        int defaultTime = 120;
        if (StringUtils.isBlank(token)) {

            String string = "";
            for (int i = 0; i < 5; i++) {

                string = HttpRequest.sendGet(getHttpUri(), "", null);

                if (StringUtils.isNoneBlank(string)) {
                    break;
                }

            }

            BTAssert.isTrue(StringUtils.isNoneBlank(string), "请求认证接口接口失败");

            JSONObject parseObject = JSONObject.parseObject(string);

            Object tokenObject = parseObject.get("access_token");
            Object expiresObject = parseObject.get("expires_in");

            if (tokenObject != null) {
                token = tokenObject.toString();
            }
            if (expiresObject != null) {
                try {
                    defaultTime = Integer.parseInt(expiresObject.toString());
                }
                catch (Exception e) {

                }
            }

            JedisUtils.set(BETTER_REDIS_TOKEN, token, defaultTime);

        }

        return token;

    }

    public static void removeToken() {

        if (JedisUtils.exists(BETTER_REDIS_TOKEN)) {
            JedisUtils.del(BETTER_REDIS_TOKEN);
        }

    }

}
